﻿var flag = true;
var moves = 0;
var P1Counter = 0, P2Counter = 0;
var P1array = new Array(), P2array = new Array();
var game = $.connection.gameHub;

$(document).ready(function () {

    $messages = $(".messages");
    $log = $(".log");
    $gamebox = $(".game-box");
    $alert = $(".alerts");
    
    //Loading the Game
    game.client.insertGame = function () {
        var content = "<table id=" + "Tic-Tack-Toe" + ">";

        content += "<tr><td id=" + "AA-11" + "><div></div></td><td id=" + "AB-12" + "><div></div></td><td id=" + "AC-13" + "><div></div></td></tr>" +
                   "<tr><td id=" + "BA-21" + "><div></div></td><td id=" + "BB-22" + "><div></div></td><td id=" + "BC-23" + "><div></div></td></tr>" +
                   "<tr><td id=" + "CA-31" + "><div></div></td><td id=" + "CB-32" + "><div></div></td><td id=" + "CC-33" + "><div></div></td></tr>";
        content += "</table>";

        content += "<span id=" + "LeftMessage" + "></span>";
        content += "<span id=" + "RightMessage" + "></span>";

        $gamebox.append(content);
    };

    //Test if we can start
    game.client.testStart = function (started) {
        if (started) {
            game.server.loadGame();
            $("#StartGame").remove();
        }
        else {
            $(".alerts span").remove();
            $alert.append("<span>" + "You Need More Players to Start the Game" + "</span>");
        }
    };

    //Register Client
    game.client.callRegister = function () {
        game.server.registerClient();
    };

/* Alerts
----------------------------------*/

        game.client.registerDone = function (Name) {
            $(".alerts span").remove();
            $alert.append("<span>" + Name + " has been added to this game" + "</span>");
        };

        game.client.playerWait = function () {
            $(".alerts span").remove();
            $alert.append("<span>" + "Wait for the other player to make his turn" + "</span>");
        };

        game.client.playerGo = function () {
            $(".alerts span").remove();
            $alert.append("<span>" + "It is Youre turn" + "</span>");
        };
        
        game.client.alertWin = function (flag) {
            $(".alerts span").remove();
            if (flag) {
                $alert.append("<span>" + "O " + " won !" + "</span>");
            }
            else {
                $alert.append("<span>" + "X " + " won !" + "</span>");
            }
            game.server.gameUpdate(flag);
        };
        
        game.client.draw = function () {
            $("#LeftMessage span").remove();
            $("#LeftMessage").html("<span>" + " The Last Game was a Draw " + "</span>")
        };

/* Tic-Tack-Toe
----------------------------------*/

        //Clean
        game.client.clean = function () {
            $("#Tic-Tack-Toe tr td div img").remove();
            P1array.length = 0;
            P2array.length = 0;
            P1Counter = 0;
            P2Counter = 0;
            moves = 0;
            flag = true;
        };
        
        //Move
        game.client.addMove = function (msg) {
            if (flag) {
                var img = $('<img class="Cross" src="/Images/X.gif" />');
                flag = false;
                var IntID = (parseInt(msg.substring(3, 5)));
                P1array[P1Counter] = IntID;
                console.log("P1: " + P1array[P1Counter]);
                P1Counter++;
            }
            else {
                var img = $('<img class="Cross" src="/Images/circle.jpg" />');
                flag = true;
                var IntID = (parseInt(msg.substring(3, 5)));
                P2array[P2Counter] = IntID;
                console.log("P2: " + P2array[P2Counter]);
                P2Counter++;
            }
            $("#" + msg + " div").append(img);
            CheckForWin(P1array);   //CheckForWin for Player-1
            CheckForWin(P2array);   //CheckForWin for Player-2
            moves++;

            if (moves == 9) {
                game.server.draw();
            }
        }

/* Click Functions
----------------------------------*/
    //Clicked on td in Tic-Tack-Toe
    $("#Tic-Tack-Toe tr td").live("click", function () {
        var ID = $(this).attr('id');
        if (CheckForEmpty(ID)) {
            game.server.sendMove(ID);
        }
    });

/* Chat
--------------------------------*/
    //When the user has connected he is added to the Log
    game.client.connected = function (frm, list, date) {
        if ($("#" + frm).length <= 0) {

            for (i = 0; i < list.length; i++) {
                $("#" + list[i]).remove();
            }

            for (i = 0; i < list.length; i++) {
                $log.append("<span id=" + list[i] + ">" + list[i] + "</span>");
            }
        }
    };

    //When the user has disconnected he is removed from the Log
    game.client.disconnected = function (frm) {
        if ($("#" + frm).length > 0)
            $("#" + frm).remove();
    };

    //Add the message
    game.client.addMessage = function (frm, msg) {
        if(msg != "" || frm != "")
            $messages.append(frm + "  : " + msg + "</br>");
    };

    //When the "Enter"(13)
    $(".messagestext").keypress(function (e) {
        if (e.which == 13) {

            //get value of input
            var input = $(this).val();

            game.server.sendMessage(input);

            $(this).val("");

        }
    });

/* Lobby
-------------------------*/
    //All Throw
    game.client.allThrow = function () {
        window.location = "/Home/Main";
    };
    //Clikc the start button
    $("#StartGame").click(function () {
        game.server.startGame();
    });

    $.connection.hub.start(function () {
        
    });
});
 
/* Tick-Tac-Toe help functions
--------------------------------*/

    //Check if colom is empty
    function CheckForEmpty(ID) {
        if (!$("#" + ID + " div").find('img').length) {
            return 1;
        }
        else {
            return 0;
        }
    }
    //Checks if player-1 or player-2 has won (Start checking at 3 moves)
    function CheckForWin(Array) {

            var sum = "S: ";

            for (var a = 0; a < Array.length; a++) {
                sum = sum + (Array[a]).toString() + ", ";
            }
            //Checking win straight down
            if (sum.indexOf("11") != -1 && sum.indexOf("21") != -1 && sum.indexOf("31") != -1 ||
                sum.indexOf("12") != -1 && sum.indexOf("22") != -1 && sum.indexOf("32") != -1 ||
                sum.indexOf("13") != -1 && sum.indexOf("23") != -1 && sum.indexOf("33") != -1) {
                if (flag) {
                    game.server.playerWon(flag);   
                }
                else {
                    game.server.playerWon(flag);
                }
            }
            //Checking win horizontal
            if (sum.indexOf("11") != -1 && sum.indexOf("12") != -1 && sum.indexOf("13") != -1 ||
                sum.indexOf("21") != -1 && sum.indexOf("22") != -1 && sum.indexOf("23") != -1 ||
                sum.indexOf("31") != -1 && sum.indexOf("32") != -1 && sum.indexOf("33") != -1) {
                if (flag) {
                    game.server.playerWon(flag);
                }
                else {
                    game.server.playerWon(flag);
                }
            }
            //Checking win diagonal
            if (sum.indexOf("11") != -1 && sum.indexOf("22") != -1 && sum.indexOf("33") != -1 ||
                sum.indexOf("13") != -1 && sum.indexOf("22") != -1 && sum.indexOf("31") != -1) {
                if (flag) {
                    game.server.playerWon(flag);
                }
                else {
                    game.server.playerWon(flag);
                }
            }
        
    }




